{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "E_RJy7C1bpCT"
   },
   "source": [
    "# Google Cloud SQL for PostgreSQL\n",
    "\n",
    "> [Cloud SQL for PostgreSQL](https://cloud.google.com/sql/docs/postgres) is a fully-managed database service that helps you set up, maintain, manage, and administer your PostgreSQL relational databases on Google Cloud Platform. Extend your database application to build AI-powered experiences leveraging Cloud SQL for PostgreSQL's Langchain integrations.\n",
    "\n",
    "This notebook goes over how to use `Cloud SQL for PostgreSQL` to load Documents with the `PostgresLoader` class.\n",
    "\n",
    "Learn more about the package on [GitHub](https://github.com/googleapis/langchain-google-cloud-sql-pg-python/).\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/googleapis/langchain-google-cloud-sql-pg-python/blob/main/docs/document_loader.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "xjcxaw6--Xyy"
   },
   "source": [
    "## Before you begin\n",
    "\n",
    "To run this notebook, you will need to do the following:\n",
    "\n",
    " * [Create a Google Cloud Project](https://developers.google.com/workspace/guides/create-project)\n",
    " * [Enable the Cloud SQL Admin API.](https://console.cloud.google.com/marketplace/product/google/sqladmin.googleapis.com)\n",
    " * [Create a Cloud SQL for PostgreSQL instance.](https://cloud.google.com/sql/docs/postgres/create-instance)\n",
    " * [Create a Cloud SQL for PostgreSQL database.](https://cloud.google.com/sql/docs/postgres/create-manage-databases)\n",
    " * [Add a User to the database.](https://cloud.google.com/sql/docs/postgres/create-manage-users)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "IR54BmgvdHT_"
   },
   "source": [
    "### 🦜🔗 Library Installation\n",
    "Install the integration library, `langchain_google_cloud_sql_pg`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "0ZITIDE160OD",
    "outputId": "90e0636e-ff34-4e1e-ad37-d2a6db4a317e"
   },
   "outputs": [],
   "source": [
    "%pip install --upgrade --quiet  langchain_google_cloud_sql_pg"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "v40bB_GMcr9f"
   },
   "source": [
    "**Colab only:** Uncomment the following cell to restart the kernel or use the button to restart the kernel. For Vertex AI Workbench you can restart the terminal using the button on top."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "6o0iGVIdDD6K"
   },
   "outputs": [],
   "source": [
    "# # Automatically restart kernel after installs so that your environment can access the new packages\n",
    "# import IPython\n",
    "\n",
    "# app = IPython.Application.instance()\n",
    "# app.kernel.do_shutdown(True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "cTXTbj4UltKf"
   },
   "source": [
    "### 🔐 Authentication\n",
    "Authenticate to Google Cloud as the IAM user logged into this notebook in order to access your Google Cloud Project.\n",
    "\n",
    "* If you are using Colab to run this notebook, use the cell below and continue.\n",
    "* If you are using Vertex AI Workbench, check out the setup instructions [here](https://github.com/GoogleCloudPlatform/generative-ai/tree/main/setup-env)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from google.colab import auth\n",
    "\n",
    "auth.authenticate_user()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Uj02bMRAc9_c"
   },
   "source": [
    "### ☁ Set Your Google Cloud Project\n",
    "Set your Google Cloud project so that you can leverage Google Cloud resources within this notebook.\n",
    "\n",
    "If you don't know your project ID, try the following:\n",
    "\n",
    "* Run `gcloud config list`.\n",
    "* Run `gcloud projects list`.\n",
    "* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "wnp1R1PYc9_c",
    "outputId": "6502c721-a2fd-451f-b946-9f7b850d5966"
   },
   "outputs": [],
   "source": [
    "# @title Project { display-mode: \"form\" }\n",
    "PROJECT_ID = \"gcp_project_id\"  # @param {type:\"string\"}\n",
    "\n",
    "# Set the project id\n",
    "! gcloud config set project {PROJECT_ID}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8f2830ee9ca1e01",
   "metadata": {
    "id": "f8f2830ee9ca1e01"
   },
   "source": [
    "## Basic Usage"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "OMvzMWRrR6n7",
   "metadata": {
    "id": "OMvzMWRrR6n7"
   },
   "source": [
    "### Set Cloud SQL database values\n",
    "Find your database variables, in the [Cloud SQL Instances page](https://console.cloud.google.com/sql/instances)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "irl7eMFnSPZr",
   "metadata": {
    "id": "irl7eMFnSPZr"
   },
   "outputs": [],
   "source": [
    "# @title Set Your Values Here { display-mode: \"form\" }\n",
    "REGION = \"us-central1\"  # @param {type: \"string\"}\n",
    "INSTANCE = \"my-primary\"  # @param {type: \"string\"}\n",
    "DATABASE = \"my-database\"  # @param {type: \"string\"}\n",
    "TABLE_NAME = \"vector_store\"  # @param {type: \"string\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "QuQigs4UoFQ2",
   "metadata": {
    "id": "QuQigs4UoFQ2"
   },
   "source": [
    "### Cloud SQL Engine\n",
    "\n",
    "One of the requirements and arguments to establish PostgreSQL as a document loader is a `PostgresEngine` object. The `PostgresEngine`  configures a connection pool to your Cloud SQL for PostgreSQL database, enabling successful connections from your application and following industry best practices.\n",
    "\n",
    "To create a `PostgresEngine` using `PostgresEngine.from_instance()` you need to provide only 4 things:\n",
    "\n",
    "1. `project_id` : Project ID of the Google Cloud Project where the Cloud SQL instance is located.\n",
    "1. `region` : Region where the Cloud SQL instance is located.\n",
    "1. `instance` : The name of the Cloud SQL instance.\n",
    "1. `database` : The name of the database to connect to on the Cloud SQL instance.\n",
    "\n",
    "By default, [IAM database authentication](https://cloud.google.com/sql/docs/postgres/iam-authentication) will be used as the method of database authentication. This library uses the IAM principal belonging to the [Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) sourced from the environment.\n",
    "\n",
    "Optionally, [built-in database authentication](https://cloud.google.com/sql/docs/postgres/users) using a username and password to access the Cloud SQL database can also be used. Just provide the optional `user` and `password` arguments to `PostgresEngine.from_instance()`:\n",
    "\n",
    "* `user` : Database user to use for built-in database authentication and login\n",
    "* `password` : Database password to use for built-in database authentication and login.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note**: This tutorial demonstrates the async interface. All async methods have corresponding sync methods."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_google_cloud_sql_pg import PostgresEngine\n",
    "\n",
    "engine = await PostgresEngine.afrom_instance(\n",
    "    project_id=PROJECT_ID,\n",
    "    region=REGION,\n",
    "    instance=INSTANCE,\n",
    "    database=DATABASE,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "e1tl0aNx7SWy"
   },
   "source": [
    "### Create PostgresLoader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "z-AZyzAQ7bsf"
   },
   "outputs": [],
   "source": [
    "from langchain_google_cloud_sql_pg import PostgresLoader\n",
    "\n",
    "# Creating a basic PostgreSQL object\n",
    "loader = await PostgresLoader.create(engine, table_name=TABLE_NAME)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "PeOMpftjc9_e"
   },
   "source": [
    "### Load Documents via default table\n",
    "The loader returns a list of Documents from the table using the first column as page_content and all other columns as metadata. The default table will have the first column as\n",
    "page_content and the second column as metadata (JSON). Each row becomes a document. Please note that if you want your documents to have ids you will need to add them in."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "cwvi_O5Wc9_e"
   },
   "outputs": [],
   "source": [
    "from langchain_google_cloud_sql_pg import PostgresLoader\n",
    "\n",
    "# Creating a basic PostgresLoader object\n",
    "loader = await PostgresLoader.create(engine, table_name=TABLE_NAME)\n",
    "\n",
    "docs = await loader.aload()\n",
    "print(docs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "kSkL9l1Hc9_e"
   },
   "source": [
    "### Load documents via custom table/metadata or custom page content columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "loader = await PostgresLoader.create(\n",
    "    engine,\n",
    "    table_name=TABLE_NAME,\n",
    "    content_columns=[\"product_name\"],  # Optional\n",
    "    metadata_columns=[\"id\"],  # Optional\n",
    ")\n",
    "docs = await loader.aload()\n",
    "print(docs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5R6h0_Cvc9_f"
   },
   "source": [
    "### Set page content format\n",
    "The loader returns a list of Documents, with one document per row, with page content in specified string format, i.e. text (space separated concatenation), JSON, YAML, CSV, etc. JSON and YAML formats include headers, while text and CSV do not include field headers.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "NGNdS7cqc9_f"
   },
   "outputs": [],
   "source": [
    "loader = await PostgresLoader.create(\n",
    "    engine,\n",
    "    table_name=\"products\",\n",
    "    content_columns=[\"product_name\", \"description\"],\n",
    "    format=\"YAML\",\n",
    ")\n",
    "docs = await loader.aload()\n",
    "print(docs)"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
